﻿using Prism.Commands;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.Net.Sockets;
using System.Text;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace 客户端.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        UdpSession udpClient = new UdpSession();
        private string _title = "Prism Application";
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        private ObservableCollection<string> _Items = new ObservableCollection<string>();
        public ObservableCollection<string> Items
        {
            get { return _Items; }
            set { SetProperty(ref _Items, value); }
        }
        public MainWindowViewModel()
        {
        }
        private string _Value;
        public string Value
        {
            get { return _Value; }
            set { SetProperty(ref _Value, value); }
        }
        public async void Initialized()
        { 
            await udpClient.SetupAsync(new TouchSocketConfig()
                //.UseUdpReceive()//作为客户端时，如果需要接收数据，那么需要绑定端口。要么使用SetBindIPHost指定端口，要么调用UseUdpReceive绑定随机端口。
                //.SetBindIPHost(new IPHost("127.0.0.1:40789"))
                ); 
            await udpClient.StartAsync();
        }
        private DelegateCommand _SendCommand;
        public DelegateCommand SendCommand =>
            _SendCommand ?? (_SendCommand = new DelegateCommand(ExecuteSendCommand));

        async void ExecuteSendCommand()
        {
            var value= Value;
            await udpClient.SendAsync(new IPHost("127.0.0.1:50789").EndPoint, Encoding.UTF8.GetBytes(value));
            Items.Add(value);
        }
    }
}
